package com.haidechizi.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class _1_两数之和 {

    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length - 1; i++) {
            int num1 = nums[i];
            for (int j = i + 1; j < nums.length; j++) {
                int num2 = nums[j];
                if(num1 + num2 == target) {
                    result[0] = i;
                    result[1]= j;
                    return result;
                }
            }
        }

        return result;
    }


    public int[] twoSum1(int[] nums, int target) {
        Map<Integer, Integer> index = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            index.put(nums[i], i);
        }
        Arrays.sort(nums);
        int[] result = new int[2];
        int low = 0, high = nums.length - 1;
        while (low < high) {
            int sum;
            if ((sum = nums[low] + nums[high]) == target) {
                result[0] = index.get(nums[low]);
                result[1] = index.get(nums[high]);
                return result;
            } else if (sum > target) {
                high--;
            } else {
                low++;
            }
        }
        return result;
    }
}
